<template>
  <el-dialog
    :model-value="isShow"
    :title="id === 0 ? '添加用户' : '编辑用户'"
    @close="offFn"
  >
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item
        label="账号："
        :label-width="formLabelWidth"
        prop="nickName"
      >
        <el-input
          v-model="form.nickName"
          placeholder="请输入账号"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item
        label="姓名："
        :label-width="formLabelWidth"
        prop="username"
      >
        <el-input
          v-model="form.username"
          placeholder="请输入姓名"
          autocomplete="off"
        />
      </el-form-item>

      <el-form-item label="邮箱：" :label-width="formLabelWidth" prop="email">
        <el-input
          v-model="form.email"
          placeholder="请输入邮箱"
          autocomplete="off"
        />
      </el-form-item>

      <el-form-item
        label="密码："
        type="password"
        :label-width="formLabelWidth"
        prop="password"
      >
        <el-input
          v-model="form.password"
          placeholder="请输入密码"
          autocomplete="off"
          type="password"
          :disabled="id !== 0"
        />
      </el-form-item>

      <el-form-item label="备注" :label-width="formLabelWidth" prop="note">
        <el-input
          v-model="form.note"
          :rows="5"
          type="textarea"
          autocomplete="off"
          placeholder="请输入备注"
        />
      </el-form-item>
      <el-form-item
        label="是否启用"
        :label-width="formLabelWidth"
        prop="status"
      >
        <el-radio-group v-model="form.status">
          <el-radio :label="1" size="large">是</el-radio>
          <el-radio :label="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emit('defaultFn')">取消</el-button>
        <el-button type="primary" @click="submitFn">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { ApiUserRegister, ApiGetUserInfo, ApiUserUpdate } from './api'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'

// 父传子
const props = defineProps({
  isShow: {
    type: Boolean,
    default: false,
  },
  id: {
    type: Number,
    default: 0,
  },
})

// 子传父
const emit = defineEmits(['defaultFn'])

// 表单数据
const form = reactive<IList>({
  username: '',
  password: '',
  email: '',
  nickName: '',
  note: '',
  status: 1,
  icon: '',
})

// 自定义校验邮箱
const validateEmail = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('🫣请输入邮箱！'))
  } else if (
    !/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)
  ) {
    callback(new Error('🫣邮箱格式有误！'))
  } else {
    callback()
  }
}

// 表单规则验证
const rules = {
  username: [
    {
      required: true,
      trigger: 'blur',
      message: '🫣请填写用户名',
    },
  ],
  password: [
    {
      required: true,
      trigger: 'blur',
      message: '🫣请填写密码',
    },
  ],
  email: [{ validator: validateEmail, required: true, trigger: 'blur' }],
  nickName: [
    {
      required: true,
      trigger: 'blur',
      message: '🫣请填写账号',
    },
  ],
  status: [
    {
      required: true,
      message: '请选择一项',
      trigger: 'change',
    },
  ],
  note: [{ trigger: 'change' }],
}

// label 宽度
const formLabelWidth = '140px'

const formRef = ref<FormInstance>()

// 添加用户
const addUser = () => {
  // 提交前最后确认框
  ElMessageBox.confirm('此操作将添加当前用户信息，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 发起添加请求
      ApiUserRegister(form).then((res) => {
        if (res.code === 200) {
          ElMessage.success('👍添加成功！')
          formRef.value?.resetFields()
          emit('defaultFn', true)
        }
      })
    })
    .catch(() => {
      ElMessage.warning('☺️您已取消！')
    })
}

// 编辑用户
const editUser = () => {
  // 提交前最后确认框
  ElMessageBox.confirm('此操作将修改当前用户信息，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      ApiUserUpdate(form).then((res) => {
        if (res.code === 200) {
          ElMessage.success('👍修改成功！')
          formRef.value?.resetFields()
          emit('defaultFn', true)
        }
      })
    })
    .catch(() => {
      ElMessage.warning('☺️您已取消！')
    })
}

// 提交表单
const submitFn = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      // 当id 变化时，判断添加与修改
      if (props.id === 0) {
        addUser()
      } else {
        editUser()
      }
    } else {
      ElMessage.warning('😩请检查表单 !')
    }
  })
}

// 对话框关闭时
const offFn = () => {
  emit('defaultFn')
  formRef.value?.resetFields()
}

// 监听id变化判断是否编辑
watch(
  () => props.id,
  () => {
    if (props.id !== 0) {
      ApiGetUserInfo(props.id).then((res) => {
        if (res.code === 200) {
          Object.assign(form, res.data)
        }
      })
    }
  },
)
</script>
<style lang="less" scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
